<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <title>个人中心</title>
    <link rel="stylesheet" type="text/css" href="../../css/api.css" />
    <link rel="stylesheet" type="text/css" href="../../css/common.css" />
    <link rel="stylesheet" type="text/css" href="../../css/aui.css" />
    <link rel="stylesheet" type="text/css" href="../../css/aui-pull-refresh.css" />
    <style>
        html,
        body {
            width: 100%;
            min-height: 100%;
            background: #f2efed;
            line-height: 1;
        }

        .chat_detail_box {
            overflow: hidden;
            overflow-y: scroll;
        }

        .chat_list {
            height: auto;
        }

        .headImg {
            width: 2rem;
            height: 2rem;
        }

        .headImg img {
            object-fit: cover;
            object-position: center center;
            height: 100%;
            width: 100%;
        }
    </style>
</head>

<body>
    <div class="chat_detail_box" v-cloak>
        <section class="aui-chat clearfix chat_list">
            <div class="aui-chat-header"></div>

            <!-- 对方的文本消息 || 自己的消息-->
            <div v-for="txt_msg in target_msg" class="aui-chat-item" :class="{'aui-chat-left':txt_msg.senderUserId != my_id,'aui-chat-right':txt_msg.senderUserId == my_id}">
                <div class="aui-chat-media headImg">
                    <img v-if="txt_msg.senderUserId == my_id" :src="my_head_img" />
                    <img v-else :src="target_head_img" />
                </div>
                <div class="aui-chat-inner">
                    <div v-if="txt_msg.senderUserId != my_id" class="aui-chat-name">{{target_name}}</div>
                    <div v-else class="aui-chat-name">{{my_name}}</div>
                    <div class="aui-chat-content">
                        <div class="aui-chat-arrow"></div>
                        <div v-if="txt_msg.objectName=='RC:TxtMsg'" v-html="txt_msg.content.text"></div>
                        <div v-else-if="txt_msg.objectName=='RC:VcMsg' && txt_msg.senderUserId == my_id" @click='to_play_amr(txt_msg.content.voicePath)'>{{txt_msg.content.duration}}s<img src='../../image/four/yy_right.png' style='vertical-align: middle;width:20px;margin-left:50px;display:inline-block;' /></div>
                        <div v-else-if="txt_msg.objectName=='RC:VcMsg' && txt_msg.senderUserId != my_id" @click='to_play_amr(txt_msg.content.voicePath)'><img src='../../image/four/yy_left.png' style='vertical-align: middle;width:20px;margin-right:50px;display:inline-block;' />{{txt_msg.content.duration}}s</div>
                        <div v-else-if="txt_msg.objectName=='RC:ImgMsg'"><img :src='txt_msg.content.imageUrl' /></div>
                    </div>
                </div>
                <div class="aui-chat-status aui-chat-status-refresh">
                    <!-- <i class="aui-iconfont aui-icon-correct aui-text-success"></i> -->
                </div>
            </div>
        </section>
    </div>
</body>
<script type="text/javascript" src="../../script/api.js"></script>
<script type="text/javascript" src="../../script/jquery.min.js"></script>
<script type="text/javascript" src="../../script/vue.min.js"></script>
<script type="text/javascript" src="../../script/common.js"></script>
<script type="text/javascript">
    var msg_detail_data;
    var frmH = 0; // 获取当前frame的高度
    var chatBox_Height = 0;
    var panel_Height = 0;
    apiready = function() {
      frmH = api.frameHeight


        var rong = api.require('rongCloud2');
        rong.init(function(ret, err) {
            if (ret.status == 'success') {
                console.log('初始化融云成功了')
            } else {
                api.toast({
                    msg: err.code
                });
            }
        });

        // // 监听最新的群聊消息
        api.addEventListener({
            name: 'new_msg_event'
        }, function(ret, err) {
            if (ret) {
                msg_detail_data.target_msg.push(ret.value.dl_msg);
                rong.clearMessagesUnreadStatus({
                    conversationType: 'PRIVATE',
                    targetId: api.pageParam.target_id
                }, function(ret, err) {
                    // console.log(ret.status);
                })
            } else {
                alert(JSON.stringify(err));
            }
        });

        // 连接融云
        rong.connect({
            token: $api.getStorage('rong-token')
        }, function(ret, err) {
            if (ret.status == 'success') {
                // console.log('融云连接成功——————————' + JSON.stringify(ret));
                //ret.result.userId;
            } else {
                alert(err.code)
            }
        });

        // 实例化vue 渲染聊天内容数据
        msg_detail_data = new Vue({
            el: '.chat_detail_box',
            data: {
                target_msg: [],
                target_name: api.pageParam.target_name,
                my_id: $api.getStorage('user_id'),
                my_name: $api.getStorage('user_name'),
                my_head_img: $api.getStorage('user_data').head_img,
                target_head_img: ''
            },
            mounted: function() {
                var $_this = this;
                rong.getLatestMessages({
                    conversationType: 'PRIVATE',
                    targetId: api.pageParam.target_id,
                    count: 20
                }, function(ret, err) {
                    if (ret) {
                        console.log('获取到的最新消息数据----' + JSON.stringify(ret))
                        $_this.target_msg = ret.result;
                        $_this.target_msg = $_this.target_msg.reverse();
                    }
                })


                // 根据对方id 获取对方的信息数据
                api.ajax({
                    url: window.Url.Community_getUserDetails,
                    method: 'post',
                    data: {
                        values: {
                            token: $api.getStorage('user_data').token,
                            user_id: api.pageParam.target_id
                        }
                    }
                }, function(ret, err) {
                    if (ret) {
                        console.log("对方的信息数据---" + JSON.stringify(ret));
                        if (ret.re == 0 && api.pageParam.target_head_img != "") {
                            $_this.target_head_img = api.pageParam.target_head_img;
                        } else {
                            $_this.target_head_img = ret.data.head_img
                        }
                    } else {
                        alert(JSON.stringify(err));
                    }
                });

            }
        })



        // 表情包图片相关数据
        var emotion_imgs = [];
        var emotion_imgs_name = [];

        //添加聊天输入框
        var UIChatTools = api.require('UIChatTools');

        UIChatTools.open({
            chatBox: {
                placeholder: '输入内容', //（可选项）字符串类型；占位提示文本，不传则无占位符
                autoFocuse: false, //（可选项）布尔类型；是否在打开时自动获取焦点，并弹出键盘；默认：false
                maxRows: 6 //（可选项）数字类型；显示的最大行数（高度自适应），超过最大行数则可上下滚动查看；默认：6
            },
            styles: {
                bgColor: '#cccccc',
                margin: 10,
            },
            tools: {
                h: 40,
                iconSize: 30,
                recorder: {
                    normal: 'fs://UIChatTolls/recorder.png',
                    selected: 'fs://UIChatTolls/recorder1.png'
                },
                image: {
                    normal: 'fs://UIChatTolls/image.png',
                    selected: 'fs://UIChatTolls/image1.png'
                },
                video: {
                    normal: 'fs://UIChatTolls/video.png',
                    selected: 'fs://UIChatTolls/video1.png'
                },
                face: {
                    normal: 'fs://UIChatTolls/face.png',
                    selected: 'fs://UIChatTolls/face1.png'
                },
                append: {
                    normal: 'fs://UIChatTolls/append.png',
                    selected: 'fs://UIChatTolls/append1.png'
                }
            },
            emotions: ['widget://res/emotions/basic', 'widget://res/emotions/append1', 'widget://res/emotions/append2']
        }, function(ret) {
            if (ret) {
                // 点击发送按钮发送文本消息
                if (ret.eventType == "send") {

                    if (ret.msg == "" || ret.msg == undefined) {
                        api.alert({
                            msg: '请输入内容'
                        })
                    } else {

                        // 发送文字+表情消息
                        if (emotion_imgs.length != 0) {
                            for (var j = 0; j < emotion_imgs.length; j++) {
                                var path = "<img style='display:inline-block;width:20px;vertical-align: middle;' src='../../res/emotions/basic/" + emotion_imgs[j] + ".png' />";
                                ret.msg = ret.msg.replace(emotion_imgs_name[j], path);
                            }
                        }
                        emotion_imgs = [];
                        emotion_imgs_name = [];

                        // 发送文本消息
                        rong.sendTextMessage({
                            conversationType: 'PRIVATE',
                            targetId: api.pageParam.target_id,
                            text: ret.msg,
                            extra: ''
                        }, function(ret, err) {
                            if (ret.status == 'prepare') {
                                console.log('文本消息发送中---' + JSON.stringify(ret.result.message));
                            } else if (ret.status == 'success') {
                                console.log('文本消息发送成功---' + ret.result.message.messageId);

                                // 文本消息发送成功重新获取最新消息数据
                                rong.getLatestMessages({
                                    conversationType: 'PRIVATE',
                                    targetId: api.pageParam.target_id,
                                    count: 20
                                }, function(ret, err) {
                                    if (ret) {
                                        msg_detail_data.target_msg = ret.result;
                                        msg_detail_data.target_msg = msg_detail_data.target_msg.reverse();

                                        // vue数据渲染完成
                                        msg_detail_data.$nextTick(function(){
                                            check_height();
                                        })
                                    }
                                })

                            } else if (ret.status == 'error') {
                                console.log('文本消息发送失败---' + err.code);
                            }

                        });

                    }
                }
                UIChatTools.clearText();
                // 点击发送按钮发送文本消息----结束

            }
        });

        // 监听输入框当前的状态  动态改变frm的显示高度

        UIChatTools.chatBoxListener({
            name: 'move'
        }, function(ret) {
            chatBox_Height = ret.chatBoxHeight;
            panel_Height = ret.panelHeight;
            // console.log('输入框move----'+JSON.stringify(ret));

            // 设定聊天列表盒子的高度
            $('.chat_detail_box').css('height', frmH - ret.chatBoxHeight - ret.panelHeight);
            var chat_boxH = frmH - ret.chatBoxHeight - ret.panelHeight;
            var listH = $('.chat_list').height();
            var to_scroll_top = listH - chat_boxH;
            $('.chat_detail_box').scrollTop(to_scroll_top);
        });
        UIChatTools.chatBoxListener({
            name: 'change'
        }, function(ret) {
            chatBox_Height = ret.chatBoxHeight;
            panel_Height = ret.panelHeight;
            // 设定聊天列表盒子的高度
            $('.chat_detail_box').css('height', frmH - ret.chatBoxHeight - ret.panelHeight);
            var chat_boxH = frmH - ret.chatBoxHeight - ret.panelHeight;
            var listH = $('.chat_list').height();
            var to_scroll_top = listH - chat_boxH;
            $('.chat_detail_box').scrollTop(to_scroll_top);
        });



        // 表情监听事件
        UIChatTools.faceListener({
            name: 'face'
        }, function(ret) {
            var click_emotion_txt = ret.text;
            api.readFile({
                path: 'widget://image/emotion/emotion.json'
            }, function(ret, err) {
                if (ret) {
                    var emotion_json = JSON.parse(ret.data);
                    // console.log('表情监听事件读取文件---'+emotion_json)
                    for (var i = 0; i < emotion_json.length; i++) {
                        if (emotion_json[i].text == click_emotion_txt) {
                            emotion_imgs.push(emotion_json[i].name);
                            emotion_imgs_name.push(emotion_json[i].text);
                        }
                    }
                }
            });
        });



        // 语音消息监听事件
        var record_path = '';
        var record_duration = '';
        UIChatTools.recorderListener(function(ret) {

            // 第一个按钮
            if (ret.eventType == 'press' && ret.target == 'talkback') {
                console.log('按下录音');
                UIChatTools.startTimer();
                api.startRecord({});
            }
            //第2个按钮
            if (ret.eventType == 'start' && ret.target == 'record') {
                UIChatTools.startTimer();
                api.startRecord({});
            } else if (ret.eventType == "stop" && ret.target == 'record') {
                console.log('点点击了第二个按钮----停止了');
            }


            //选择试听
            if (ret.eventType == 'auditionTouchOn') {
                //停止录音
                api.stopRecord(function(ret, err) {
                    if (ret) {
                        path = ret.path;
                        duration = ret.duration;

                        api.startPlay({
                            path: path
                        }, function(ret, err) {
                            if (ret) {
                                console.log('播放完成');
                            } else {
                                console.log(JSON.stringify(err));
                            }
                        });

                    }
                });
            }


            // 发送音频
            if (ret.eventType == 'send' && ret.target == 'talkback') {
                api.stopRecord(function(ret, err) {
                    var record_path2 = '';
                    var record_duration2 = '';
                    if (ret) {
                        // console.log('这里是停止录音' + JSON.stringify(ret));
                        record_path2 = ret.path;
                        record_duration2 = ret.duration;


                        rong.sendVoiceMessage({
                            conversationType: 'PRIVATE',
                            targetId: api.pageParam.target_id,
                            voicePath: record_path2,
                            duration: record_duration2,
                            extra: ''
                        }, function(ret, err) {

                            if (ret.status == 'prepare') {
                                // console.log('语音准备发送222');
                            } else if (ret.status == 'success') {
                                // console.log('语音消息发送成功222');
                                //文本消息发送成功重新获取最新消息数据
                                rong.getLatestMessages({
                                    conversationType: 'PRIVATE',
                                    targetId: api.pageParam.target_id,
                                    count: 20
                                }, function(ret, err) {

                                    if (ret) {
                                        msg_detail_data.target_msg = ret.result;
                                        msg_detail_data.target_msg = msg_detail_data.target_msg.reverse();
                                        // console.log(JSON.stringify(msg_detail_data))

                                        // vue数据渲染完成
                                        msg_detail_data.$nextTick(function(){
                                            check_height();
                                        })
                                    }
                                })
                            } else if (ret.status == 'error') {
                                console.log('语音消息发送失败22' + err.code);
                            }
                        });

                    }
                });
            } else if (ret.eventType == 'send' && ret.target == 'record') {
                api.stopRecord(function(ret, err) {
                    var record_path3 = '';
                    var record_duration3 = '';
                    if (ret) {
                        // console.log('这里是停止录音' + JSON.stringify(ret));
                        record_path3 = ret.path;
                        record_duration3 = ret.duration;

                        rong.sendVoiceMessage({
                            conversationType: 'PRIVATE',
                            targetId: api.pageParam.target_id,
                            voicePath: record_path3,
                            duration: record_duration3,
                            extra: ''
                        }, function(ret, err) {

                            if (ret.status == 'prepare') {
                                // console.log('语音准备发送222');
                            } else if (ret.status == 'success') {
                                //文本消息发送成功重新获取最新消息数据
                                rong.getLatestMessages({
                                    conversationType: 'PRIVATE',
                                    targetId: api.pageParam.target_id,
                                    count: 20
                                }, function(ret, err) {

                                    if (ret) {
                                        msg_detail_data.target_msg = ret.result;
                                        msg_detail_data.target_msg = msg_detail_data.target_msg.reverse();
                                        // console.log(JSON.stringify(msg_detail_data))

                                        // vue数据渲染完成
                                        msg_detail_data.$nextTick(function(){
                                            check_height();
                                        })
                                    }
                                })
                            } else if (ret.status == 'error') {
                                console.log('语音消息发送失败22' + err.code);
                            }
                        });
                    }
                });

            }

        });




        // 图片发送监听
        UIChatTools.imageListener(function(ret) {
            //相册
            if (ret.eventType == 'album') {

                api.getPicture({
                    sourceType: 'library',
                    encodingType: 'png',
                    mediaValue: 'pic',
                    destinationType: 'url',
                    allowEdit: true,
                    quality: 100,
                    saveToPhotoAlbum: false
                }, function(ret, err) {
                    if (ret) {
                        //  console.log("从本地选择图片成功 --- "+JSON.stringify(ret));
                        UIChatTools.closeBoard();
                        rong.sendImageMessage({
                            conversationType: 'PRIVATE',
                            targetId: api.pageParam.target_id,
                            imagePath: ret.data,
                            extra: ''
                        }, function(ret, err) {
                            // console.log('从相册选择图片' + JSON.stringify(ret));
                            if (ret.status == 'prepare') {

                            } else if (ret.status == 'progress') {

                            } else if (ret.status == 'success') {
                                console.log('从相册选择图片发送成功');

                                //文本消息发送成功重新获取最新消息数据
                                rong.getLatestMessages({
                                    conversationType: 'PRIVATE',
                                    targetId: api.pageParam.target_id,
                                    count: 20
                                }, function(ret, err) {

                                    if (ret) {
                                        msg_detail_data.target_msg = ret.result;
                                        msg_detail_data.target_msg = msg_detail_data.target_msg.reverse();
                                        // console.log(JSON.stringify(msg_detail_data))


                                        // vue数据渲染完成
                                        msg_detail_data.$nextTick(function(){
                                            check_height();
                                        })
                                    }
                                })


                            } else if (ret.status == 'error') {
                                console.log('从相册选择图片发送失败');
                            }
                        });

                    } else {
                        console.log("从相册选择图片失败 --- " + JSON.stringify(err));
                    }
                });

            }


            //点击了编辑
            if (ret.eventType == 'edit') {
                // console.log('点击了编辑');
                api.alert({
                    msg: '还未编写该页面'
                });
            }


            if (ret.eventType == "send" && ret.images.length != 0) {
                UIChatTools.closeBoard();
                for (var i = 0; i < ret.images.length; i++) {

                    (function() {
                        var x = i;
                        rong.sendImageMessage({
                            conversationType: 'PRIVATE',
                            targetId: api.pageParam.target_id,
                            imagePath: ret.images[x],
                            extra: ''
                        }, function(ret, err) {
                            // console.log('从相册选择图片' + JSON.stringify(ret));
                            if (ret.status == 'prepare') {

                            } else if (ret.status == 'progress') {

                            } else if (ret.status == 'success') {
                                console.log('从相册选择图片发送成功');

                                //文本消息发送成功重新获取最新消息数据
                                rong.getLatestMessages({
                                    conversationType: 'PRIVATE',
                                    targetId: api.pageParam.target_id,
                                    count: 20
                                }, function(ret, err) {

                                    if (ret) {
                                        msg_detail_data.target_msg = ret.result;
                                        msg_detail_data.target_msg = msg_detail_data.target_msg.reverse();
                                        // console.log(JSON.stringify(msg_detail_data))


                                        // vue数据渲染完成
                                        msg_detail_data.$nextTick(function(){
                                          setTimeout(function(){
                                            check_height();
                                          },500)
                                        })
                                    }
                                })


                            } else if (ret.status == 'error') {
                                console.log('从相册选择图片发送失败');
                            }
                        });
                    })()
                }
            }
        });



        // 拍照发送
        UIChatTools.toolsListener(function(ret) {
            if (ret.eventType == 'video') {

                api.getPicture({
                    sourceType: 'camera',
                    encodingType: 'png',
                    mediaValue: 'pic',
                    destinationType: 'url',
                    allowEdit: true,
                    quality: 100,
                    saveToPhotoAlbum: false
                }, function(ret, err) {
                    if (ret) {
                        //  console.log("从本地选择图片成功 --- "+JSON.stringify(ret));
                        UIChatTools.closeBoard();
                        rong.sendImageMessage({
                            conversationType: 'PRIVATE',
                            targetId: api.pageParam.target_id,
                            imagePath: ret.data,
                            extra: ''
                        }, function(ret, err) {
                            // console.log('从相册选择图片' + JSON.stringify(ret));
                            if (ret.status == 'prepare') {

                            } else if (ret.status == 'progress') {

                            } else if (ret.status == 'success') {
                                console.log('从拍照发送成功');

                                //文本消息发送成功重新获取最新消息数据
                                rong.getLatestMessages({
                                    conversationType: 'PRIVATE',
                                    targetId: api.pageParam.target_id,
                                    count: 20
                                }, function(ret, err) {

                                    if (ret) {
                                        msg_detail_data.target_msg = ret.result;
                                        msg_detail_data.target_msg = msg_detail_data.target_msg.reverse();
                                        // console.log(JSON.stringify(msg_detail_data))

                                        // vue数据渲染完成
                                        msg_detail_data.$nextTick(function(){
                                            check_height();
                                        })
                                    }
                                })


                            } else if (ret.status == 'error') {
                                console.log('从拍照发送失败');
                            }
                        });


                    } else {
                        console.log("拍照发送失败22 --- " + JSON.stringify(err));
                    }
                });


            } else if (ret.eventType == 'append') {
                console.log('附加按钮');
                api.toast({
                    msg: '暂未开通',
                    duration: 2000,
                    location: 'bottom'
                });
            }
        });

    };


    // 播放发送的音频文件
    function to_play_amr(path) {
        console.log(path);
        api.startPlay({
            path: path
        }, function(ret, err) {
            if (ret) {
                console.log('播放完成');
            } else {
                console.log(JSON.stringify(err));
            }
        });
    }

    function check_height() {
        // 设定聊天列表盒子的高度
        $('.chat_detail_box').css('height', frmH - chatBox_Height - panel_Height);
        var chat_boxH = frmH - chatBox_Height - panel_Height;
        var listH = $('.chat_list').height();
        var to_scroll_top = listH - chat_boxH;
        $('.chat_detail_box').scrollTop(to_scroll_top);
    }
</script>

</html>
